const express = require("express");
const router = express.Router();
const models = require("../models");
const Op = models.Sequelize.Op; // 模糊查询的时候需要用到

// 查询社团列表
router.get("/", async function (req, res, next) {
  const where = {};
  const currentPage = parseInt(req.query.currentPage) || 1; // 分页参数
  const pageSize = parseInt(req.query.pageSize) || 10; // 分页参数
  const name = req.query.name;
  const type = req.query.type;
  const status = req.query.status;
  const society = req.query.society;
  if (name) {
    where.name = {
      [Op.like]: "%" + name + "%",
    };
  }
  if (type) {
    where.type = {
      [Op.like]: type,
    };
  }
  if (status) {
    where.status = {
      [Op.like]: status,
    };
  }
  if (society) {
    where.id = {
      [Op.in]: society,
    };
  }
  const result = await models.Society.findAndCountAll({
    order: [["id", "desc"]], // 根据某个字段进行排序， desc-降序 asc-升序
    where: where,
    offset: (currentPage - 1) * pageSize,
    limit: pageSize,
  });
  res.json({
    code: 200,
    msg: "操作成功",
    data: {
      total: result.count,
      currentPage: currentPage,
      pageSize: pageSize,
      data: result.rows,
    },
  });
});

// 新增社团
router.post("/", async function (req, res, next) {
  await models.Society.create({
    name: req.body.name,
    introduce: req.body.introduce,
    nowNumber: req.body.nowNumber,
    planNumber: req.body.planNumber,
    minister: req.body.minister,
    imgurl: req.body.imgurl,
    status: 0, // 默认创建就开始招新
  });
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 查询社团
router.get("/:id", async function (req, res, next) {
  const data = await models.Society.findByPk(req.params.id);
  res.json({
    code: 200,
    msg: "操作成功",
    data: data,
  });
});

// 修改社团
router.put("/", async function (req, res, next) {
  // findByPk是通过主键查找
  const result = await models.Society.findByPk(req.body.id);
  result.update(req.body);
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 删除社团
router.delete("/:id", async function (req, res, next) {
  const result = await models.Society.findByPk(req.params.id);
  result.destroy(req.body);
  res.json({
    code: 200,
    msg: "操作成功",
  });
});

// 查询指定社团
router.delete("/:id", async function (req, res, next) {
  const result = await models.Society.findByPk(req.params.id);
  res.json({
    code: 200,
    msg: "操作成功",
    data: result,
  });
});

module.exports = router;
